/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.joinus.home.core;

import java.io.IOException;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import br.ufes.cwtools.joinus.util.DBHelper;
import br.ufes.cwtools.joinus.util.ServerCom;

import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class NewInvitations {
	double lat, lon, radius;
	static final int NONE=0, WAITING_RESPONSE=1, REQUEST_DENIED=2, JOINED=3, INVITATION_IGNORED=4;
	private String campName, authorName="?", desc, isPublic;
	String creation, expiration;
	long id;
	int status;

	public Vector<NewInvitations> fromXml(InputSource xml) {
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp;
			sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			InvitationsHandler handler = new InvitationsHandler();
			xr.setContentHandler(handler);
			Log.d("NewInvitations", "Will parse XML now.");
			xr.parse(xml);
			return handler.getInvitations();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/*
	 * Classe para processar o arquivo XML de invitations.
	 * Reescrita para substituir "MyHandler", usada anteriormente.
	 * Referência: http://www.ibm.com/developerworks/opensource/library/x-android/
	 * */
	class InvitationsHandler extends DefaultHandler {
		private StringBuilder builder;
		private NewInvitations currentInvitation;
		private Vector<NewInvitations> invitations = null;
		
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
			builder = new StringBuilder();
			invitations = new Vector<NewInvitations>();
		}
		
		public Vector<NewInvitations> getInvitations() {
			return this.invitations;
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			if (localName.equalsIgnoreCase("Campaign")) {
				currentInvitation = new NewInvitations();
			}
			builder.setLength(0);
		}
		
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			super.characters(ch, start, length);
			builder.append(ch, start, length);
		}
		
		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			super.endElement(uri, localName, qName);
			if (currentInvitation != null) {
				String content = builder.toString().trim();
				if (localName.equalsIgnoreCase("Campaign")) {
					invitations.add(currentInvitation);
					currentInvitation = null;
				} else if (content.length() > 0) {
					Log.d("InvitationsHandler.endElement", localName + ": " + content);
					if (localName.equalsIgnoreCase("idCampaign")) {
						try {
							currentInvitation.id = Integer.parseInt(content);
						} catch (Exception e) {
							currentInvitation = null;
						}
					} else if (localName.equalsIgnoreCase("name")) {
						currentInvitation.campName = content;
					} else if (localName.equalsIgnoreCase("description")) {
						currentInvitation.desc = content;
					} else if (localName.equalsIgnoreCase("area")) {
						try {
							content = content.replace('(', ' ');
							content = content.replace(')', ' ');
							String[] values = content.split(",");
							currentInvitation.lat = Double.parseDouble(values[0]);
							currentInvitation.lon = Double.parseDouble(values[1]);
							currentInvitation.radius = Double.parseDouble(values[2]);
						} catch (Exception e) {
							currentInvitation.lat = 0.0;
							currentInvitation.lon = 0.0;
							currentInvitation.radius = 0.0;
						}
					} else if (localName.equalsIgnoreCase("creation")) {
						currentInvitation.creation = content;
					} else if (localName.equalsIgnoreCase("expiration")) {
						currentInvitation.expiration = content;
					} else if (localName.equalsIgnoreCase("idProfile")) {
						currentInvitation.authorName = content;
					} else if (localName.equalsIgnoreCase("publicCamp")) {
						currentInvitation.isPublic = content;
					}
				}
			}
		}
	}

//	public static NewInvitations[] fromDataBase() {
//		return null;
//	} //TODO
	
//	public String toXml() {
//		return null;
//	} // TODO

	public boolean toDataBase(SQLiteDatabase db, String user){
		try {
			DBHelper toRecord = new DBHelper();
			toRecord.onCreate(db);
			db.execSQL("INSERT INTO activeInvitations (id, campName, authorName, desc, expDate, status, user, public) values("+
					id+", '"+campName+"', '"+ServerCom.getUserName(authorName)+"', '"+desc+"' ,'"+expiration.toString()+"', "+status+",'"+user+"','"+isPublic+"');");

			return true;
		} catch (SQLException e) {
			Log.d("DEBUG","db 4 error");
			return false;
		}
	}

//	public String getCampName() {
//		return campName;
//	}
}
